/**
 * admin/sessions
 */

const URL = require('url');
const lodash = require('lodash');
const passport = require('koa-passport');

module.exports = function(app) {
    const router = app.router;
    const apiRouter = app.apiRouter;

    // 登录 - Admin
    apiRouter.post('/sessions', passport.authenticate('admin', {
        failWithError: true
    }), function * () {
        const user = this.req.user.clone();

        // Clean
        user.unset('grade');

        this.body = user;
    });


    // 注销
    apiRouter.delete('/sessions', function *() {
        this.logout();

        this.body = {
            status: 'success'
        };
    });

    // OAuth
    const oauthCallbackAllowHosts = [
        'admin.xsbapp.dev',
        'admin.xsbapp.com'
    ];

    const genOAuthPrecheckMW = function(type) {
        return function *(ctx, next) {
            let query = this.query;

            // redirect to oauth server
            if(!('code' in query)) {
                yield passport.authenticate(type, {
                    state: 'www'
                });

                return;
            }

            // local/stage env
            let localUrl = lodash.trim(query.r);
            if(localUrl) {
                let localUrlData = URL.parse(localUrl, true);

                if(oauthCallbackAllowHosts.indexOf(localUrlData.hostname) < 0) {
                    this.throw(400, 'Callback redirect url not allowed');
                }

                // mixin query
                lodash.assign(localUrlData.query, this.query);

                // clean
                delete localUrlData.query.r;

                // redirect to local/stage env
                this.redirect(localUrlData.format());

                return;
            }

            yield next;
        };
    };

    // 登入 - Weibo callback
    router.get('/sessions/weibo',
        genOAuthPrecheckMW('weibo'),
        passport.authenticate('weibo'),
        function *() {
            this.redirect('back', '/');
        });

    // 登入 - Wechat callback
    router.get('/sessions/wechat',
        genOAuthPrecheckMW('wechat'),
        passport.authenticate('wechat'),
        function *() {
            this.redirect('back', '/');
        });
};
